package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.Arrays;

/**
 * <a href="https://leetcode.cn/problems/rotate-image/description/?envType=study-plan-v2&envId=top-100-liked">旋转图像</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-27 20:56:12
 */
public class HotCode020 {
    public static void main(String[] args) {
        int[][] matrix = {
                {5,1,9,11},
                {2,4,8,10},
                {13,3,6,7},
                {15,14,12,16}
        };
        HotCode020 hotCode020 = new HotCode020();
        Arrays.stream(matrix).forEach(array -> System.out.println(Arrays.toString(array)));
        hotCode020.rotate(matrix);
        System.out.println("---------------");
        Arrays.stream(matrix).forEach(array -> System.out.println(Arrays.toString(array)));
    }

    public void rotate(int[][] matrix) {
        int length = matrix.length;
        if (length == 1) {
            return;
        }
        int top = 0, down = length - 1, left = 0, right = length - 1;
        while (top < down && left < right) {
            rotate(matrix, top, down, left, right);
            top++;
            down--;
            left++;
            right--;
        }
    }

    public void rotate(int[][] matrix, int top, int down, int left, int right) {
        int[] temp = new int[4];
        for (int index = 0; index < right - left; index++) {
            temp[0] = matrix[top][left + index];
            temp[1] = matrix[top + index][right];
            temp[2] = matrix[down][right - index];
            temp[3] = matrix[down - index][left];
            matrix[top][left + index] = temp[3];
            matrix[top + index][right] = temp[0];
            matrix[down][right - index] = temp[1];
            matrix[down - index][left] = temp[2];
        }
    }
}
